package org.jeecg.modules.supervise.typeHandler;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;

import java.util.List;
import java.util.function.BiConsumer;

/**
 * @title: SqlBatchHelper
 * @Author Qiulei
 * @Date: 2023/11/2 17:22
 */
public class SqlBatchHelper {

    /**
     * 根据条件批量修改数据
     * @param mapperClass
     * @param entityClass
     * @param list
     * @param biconsumer 以下为示例
     *                   (lambdaUpdateWrapper, entity)->{
     *                              lambdaUpdateWrapper.eq(Entity::getProper,"具体值 或 entity.getProper");
     *                   }
     * @param <M>
     * @param <E>
     */
    public static <M extends BaseMapper<E>,E> void updateBatch(Class<M> mapperClass,Class<E> entityClass, List<E> list, BiConsumer<LambdaUpdateWrapper<E>,E> biconsumer){
        batchExecutor(mapperClass,entityClass,list,(mapper,entity)->{
            LambdaUpdateWrapper<E> lambdaUpdateWrapper = Wrappers.lambdaUpdate(entityClass);
            biconsumer.accept(lambdaUpdateWrapper,entity);
            mapper.update(entity,lambdaUpdateWrapper);
        });
    }

    /**
     * 批量插入数据
     * @param mapperClass Mapper 类型
     * @param list 数据
     * @param <M>
     * @param <E>
     */
    public static <M extends BaseMapper<E>,E> void insertBatch(Class<M> mapperClass,Class<E> entityClass, List<E> list){
        batchExecutor(mapperClass,entityClass,list,(mapper,entity)->{
            mapper.insert(entity);
        });
    }



    /**
     *
     * @param mapperClass Mapper 类型
     * @param list  数据
     * @param biconsumer 如何操作具体操作
     * @param <M>
     * @param <E>
     */
    public static  <M extends BaseMapper<E>,E> void  batchExecutor(Class<M> mapperClass,Class<E> entityClass, List<E> list, BiConsumer<M,E> biconsumer){
        SqlSession sqlSession = SqlHelper.sqlSessionFactory(entityClass).openSession(ExecutorType.BATCH);
        M mapper = sqlSession.getMapper(mapperClass);
        list.stream().forEach(entity->biconsumer.accept(mapper,entity));
        sqlSession.flushStatements();
        sqlSession.clearCache();
    }



}
